package cn.itcast.star.graph.core.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.BCrypt;
import cn.itcast.star.graph.core.pojo.dto.request.UserLoginReqDTO;
import cn.itcast.star.graph.core.pojo.dto.respone.UserLoginResDTO;
import cn.itcast.star.graph.core.mapper.UserMapper;
import cn.itcast.star.graph.core.pojo.User;
import cn.itcast.star.graph.core.service.UserService;
import cn.itcast.star.graph.core.utils.JWTUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.coyote.BadRequestException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * sg_user Service 接口实现
 * </p>
 *
 * @author miukoo
 * @since 2024-08-12 09:59:06
 */
@Service
@Transactional
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public UserLoginResDTO loginByPassword(UserLoginReqDTO userLoginReqDTO) throws BadRequestException {
        // 手机号
        if(StrUtil.isEmpty(userLoginReqDTO.getUsername())
                || StrUtil.isEmpty(userLoginReqDTO.getPassword())) {
            throw new BadRequestException("账号或密码不能为空");
        }
        // 用户名输入框同时能接受：手机号码、用户名两个信息
        // where mobile like '' or username like ''
        User user = lambdaQuery()
                .or(StrUtil.isNotEmpty(userLoginReqDTO.getUsername()),(c)->{
                    c.eq(User::getMobile, userLoginReqDTO.getUsername());
                })
                .or(StrUtil.isNotEmpty(userLoginReqDTO.getUsername()),(c)->{
                    c.eq(User::getUsername, userLoginReqDTO.getUsername());
                })
                .one();
        if(user == null || !BCrypt.checkpw(userLoginReqDTO.getPassword(), user.getPassword())) {
            throw new BadRequestException("手机号或密码不匹配");
        }
        return generateLoginInfo(user);
    }

    private UserLoginResDTO generateLoginInfo(User user) {
        UserLoginResDTO userLoginResDTO = BeanUtil.toBean(user, UserLoginResDTO.class);
        if(StrUtil.isEmpty(userLoginResDTO.getName())){
            userLoginResDTO.setName(user.getUsername());
        }
        if(StrUtil.isEmpty(userLoginResDTO.getName())){
            userLoginResDTO.setName(user.getMobile());
        }
        // 生成token
        userLoginResDTO.setToken(JWTUtils.createJWT(userLoginResDTO.getId(),userLoginResDTO.getName()));
        return userLoginResDTO;
    }

}